package com.ruoyi.WELD.controller;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.WELD.domain.Weld;
import com.ruoyi.WELD.domain.Welding;
import com.ruoyi.WELD.service.IWeldingService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/Welding/welding")
public class WeldingController extends BaseController
{
    @Autowired
    private IWeldingService weldingService;

    /*查询*/
    @GetMapping("/list")
    public TableDataInfo list(Welding welding) {
        startPage();
        List<Welding> list = weldingService.selectWeldingList(welding);
        return getDataTable(list);
    }
    @GetMapping("/listAll")
    public TableDataInfo listAll(Welding welding) {
        List<Welding> list = weldingService.selectWeldingList(welding);
        return getDataTable(list);
    }

    /*获取*/
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") Long ID)
    {
        return success(weldingService.selectWeldingById(ID));
    }

    /*新增*/
    @PostMapping
    public AjaxResult add(@RequestBody Welding welding)
    {
        return toAjax(weldingService.insertWelding(welding));
    }

    /*修改*/
    @PutMapping
    public AjaxResult edit(@RequestBody Welding welding)
    {
        return toAjax(weldingService.updateWelding(welding));
    }

    /*删除*/
    @DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable Long[] IDs)
    {
        return toAjax(weldingService.deleteWeldingByIds(IDs));
    }

    /*清空数据库*/
    @DeleteMapping("/clear")
    public AjaxResult clearAllWelding()
    {
        try{
            weldingService.ClearWelding();
            return toAjax(1);
        }catch (Exception e){
            return toAjax(0);
        }
    }

    /*导出*/
    @PostMapping("/export1")
    public void export1(Long[] ids,HttpServletResponse response)
    {
       List<Welding> list = weldingService.selectWeldingByIds(ids);
        weldingService.exportByTemplate1(list,response);
    }

    @PostMapping("/export2")
    public void export2(Long[] ids,HttpServletResponse response)
    {
        List<Welding> list = weldingService.selectWeldingByIds(ids);
        weldingService.exportByTemplate2(list,response);
    }
    /*根据id来导出全部*/
    @PostMapping("/export3")
    public void export3(Long[] ids,HttpServletResponse response)
    {
        List<Welding> list = weldingService.selectWeldingByIds(ids);
        ExcelUtil<Welding> util = new ExcelUtil<>(Welding.class);
        util.exportExcel(response, list, "数据");
    }
    /*导出全部，默认全选*/
    @PostMapping("/exportAll")
    public void exportAll(Welding welding,HttpServletResponse response)
    {
        List<Welding> list = weldingService.selectWeldingList(welding);
        ExcelUtil<Welding> util = new ExcelUtil<>(Welding.class);
        util.exportExcel(response, list, "数据");
    }
    /*导出2全部，默认全选*/
    @PostMapping("/exportAll2")
    public void exportAll2(Welding welding,HttpServletResponse response)
    {
        List<Welding> list = weldingService.selectWeldingList(welding);
        weldingService.exportByTemplate3(list,response);
    }

    /*导入模版*/
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<Welding> util = new ExcelUtil<>(Welding.class);
        util.importTemplateExcel(response, "数据");
    }

    @PostMapping("/importData")
    public AjaxResult importEasyExcel(MultipartFile file,boolean updateSupport) throws IOException {
        WeldingImportListener listener = new WeldingImportListener();
        if (file.getOriginalFilename().toLowerCase().endsWith(".csv")){
            int emptyCnt =0;
            int headRow = 0;
            try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                int rowIdx = 1;
                while ((line = br.readLine()) != null) {
                    if (line.isEmpty()) {
                        emptyCnt++;          // 记录空行
                    } else if (line.startsWith("NO.")) {   // 或 JEID/Product 等表头关键字
                        headRow = rowIdx;
                        break;
                    }
                    rowIdx++;
                }
            }
            EasyExcel.read(file.getInputStream(), listener)
                    .sheet()
                    .headRowNumber(headRow)
                    .doRead();
            if (listener.getList().isEmpty()) {
                listener = new WeldingImportListener();          // 重置
                int fallbackRow = Math.max(headRow - emptyCnt, 0);
                EasyExcel.read(file.getInputStream(), listener)
                        .sheet()
                        .headRowNumber(fallbackRow)
                        .doRead();
            }
        }else {
            EasyExcel.read(file.getInputStream(), listener)
                    .sheet()
                    .doRead();
        }
        List<Welding> list = listener.getList();
        String message = weldingService.importWelding(list, updateSupport);

        // TODO: service.saveBatch(list);
        return success(message);
    }


    /*自动匹配参数*/
    @GetMapping("/generate")
    public AjaxResult generate(Welding welding, Weld weld)
    {
        String message=weldingService.GenerateUpdate(welding,weld);
        return success(message);
    }
}